<template>
  <pages-container
    :loading="pageLoading"
    loading-text="数据加载中..."
    :loading-text-style="{ color: '#999' }"
  >
    <view>
      分享参数：
      <text>{{ shareData }}</text>
    </view>
    <view>
      解析数据：
      <text>{{ parseData }}</text>
    </view>
    <image class="w-400rpx h-400rpx mx-auto mt-20vh" :src="qrcodeUrl"></image>
  </pages-container>
</template>

<script lang="ts">
import { isEmpty } from 'lodash-es'
import { Component, Vue } from 'vue-property-decorator'

import { appStore, userStore } from '@/store/modules'
import { openMiniAppHelper, parseQrcode, showModal, showToast } from '@/utils'

@Component({ name: 'Qrcode' })
export default class Qrcode extends Vue {
  pageLoading = true

  qrcodeUrl = ''
  shareData = ''
  parseData = ''

  async onLoad(query: AnyObject) {
    const { checkAuth, tenantId, path } = await parseQrcode(query)
    if (tenantId && appStore.tenantId !== tenantId) {
      appStore.setSelectTenant(tenantId)
      uni.setStorageSync('lastTenantId', tenantId)
      try {
        await userStore.Login({ loginType: 3, tenantId })
      } catch (e) {
        await userStore.Login({ loginType: 2, tenantId })
      }
      uni.$emit('tenant:ok')
    }

    if (checkAuth) {
      if (!userStore.getToken) {
        await userStore.Login({ loginType: 2 })
      }

      if (isEmpty(userStore.authUserInfo.paasPeople)) {
        // 需要实名认证
        await showModal({
          title: '提示',
          content: '您还未实名认证，点击确认前往实名认证？',
          confirmText: '前往',
          showCancel: false
        })

        await new Promise((resolve) => {
          this.registerAuthCallback(resolve)
          openMiniAppHelper(
            {
              extraData: {
                token: userStore.getToken
              }
            },
            { envVersion: 'trial' }
          )
        })
      }
    }

    path
      ? uni.redirectTo({
          url: path
        })
      : uni.reLaunch({
          url: '/pages/redirect/index'
        })
  }

  registerAuthCallback(cb: Fn) {
    const callback = async ({ referrerInfo }: AnyObject) => {
      if (
        referrerInfo &&
        referrerInfo.extraData &&
        referrerInfo.extraData.success
      ) {
        uni.offAppShow(callback)
        await userStore.Login({ loginType: 2 })
        await showToast('实名认证成功！')
        cb()
      }
    }
    uni.onAppShow(callback)
  }
}
</script>
